package cn.gok.service;

import cn.gok.dao.SqlDao;
import cn.gok.tool.Compare;
import cn.gok.tool.Jdbc;
import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
import java.util.List;

public class SqlService {

    public JSONObject selvalidation(JSONObject json){
        Compare compare=new Compare();
        SqlDao sqlDao=new SqlDao();
        JSONObject res=new JSONObject();
        String port=json.getString("port");
        String database=json.getString("database");
        String username=json.getString("username");
        String password=json.getString("password");
        String url=json.getString("url");
        Jdbc jdbc=new Jdbc();
        url=compare.tourl(url,port,database);
        jdbc.setURL(url);
        jdbc.setUser_Name(username);
        jdbc.setUser_PSW(password);
        List<String> sql=compare.toString(json.getString("sql"));
        List<String> answer=compare.toString(json.getString("answer"));
        String tp="";
        if(sql.size()!=answer.size()){
            res.put("code",0);
            res.put("msg","正确答案与待测语句数量不匹配！");
        }
        else {
            for (int i = 0; i <answer.size() ; i++) {
                List list1 =sqlDao.sel(jdbc,answer.get(i));
                List list2 =sqlDao.sel(jdbc,sql.get(i));
//                添加sql语句报错的处理
                if(list1==null){
                    res.put("code",0);
                    res.put("msg","答案sql语句出错:"+answer.get(i));
                    return res;
                }
                if(list2==null){
                    res.put("code",0);
                    res.put("msg","测试sql语句出错:"+sql.get(i));
                    return res;
                }
                if(compare.validation(list1,list2)){
                    System.out.println(sql.get(i)+"答案正确");
                }else{
                    int num=i+1;
                    tp=tp+"第"+num+"题";
                }

            }

        }
        if(tp==""){
            res.put("code",1);
            res.put("msg","恭喜你，全部正确哦！");
        }else{
            res.put("code",0);
            res.put("msg","答错的题目有:"+tp);
        }

        return res;
    }
}
